package cn.iocoder.yudao.module.member.agency.api;

import cn.hutool.core.collection.CollStreamUtil;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.api.member.agency.AgencyUserApi;
import cn.iocoder.yudao.module.api.member.agency.enums.AgencyLevelEnum;
import cn.iocoder.yudao.module.api.member.agency.vo.AgencyApplyVO;
import cn.iocoder.yudao.module.api.member.agency.vo.AgencyUserVO;
import cn.iocoder.yudao.module.member.agency.dal.dataobject.AgencyApplyDO;
import cn.iocoder.yudao.module.member.agency.dal.dataobject.AgencyUserDO;
import cn.iocoder.yudao.module.member.agency.service.AdminAgencyUserService;
import cn.iocoder.yudao.module.member.agency.service.AgencyApplyService;
import cn.iocoder.yudao.module.member.agency.service.AppAgencyUserService;
import cn.iocoder.yudao.module.member.agency.vo.AppAgencyUserVO;
import jakarta.annotation.Nullable;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 招商人员的 API 实现类
 *
 * @author 山野羡民
 */
@Service
@Validated
public class AgencyUserApiImpl implements AgencyUserApi {

    @Resource
    private AgencyApplyService agencyApplyService;
    @Resource
    private AppAgencyUserService appAgencyUserService;
    @Resource
    private AdminAgencyUserService adminAgencyUserService;

    @Override
    public AgencyApplyVO getApplyInfo(Long userId) {
        AgencyApplyDO entity = agencyApplyService.getDetailByUserId(userId, null);
        return BeanUtils.toBean(entity, AgencyApplyVO.class);
    }

    @Override
    public AgencyUserVO getAgencyUser(Long id) {
        AppAgencyUserVO vo = appAgencyUserService.getDetail(id);
        return BeanUtils.toBean(vo, AgencyUserVO.class);
    }

    @Override
    public AgencyUserVO getAgencyUserByUserId(Long userId) {
        AgencyUserDO entity = appAgencyUserService.getOrCreate(userId);
        return BeanUtils.toBean(entity, AgencyUserVO.class);
    }

    @Override
    public boolean validAgency(Long userId, @Nullable AgencyLevelEnum level) {
        return appAgencyUserService.isValid(userId, level);
    }

    @Override
    public boolean validAgency(Long agencyId) {
        AppAgencyUserVO respVO = appAgencyUserService.getDetail(agencyId);
        if (respVO == null) {
            return false;
        }
        return validAgency(respVO.getUserId(), null);
    }

    @Override
    public Map<Long, AgencyUserVO> getAgencyUserMap(Set<Long> agencyUserIds) {
        List<AgencyUserVO> list = adminAgencyUserService.getListByUserIds(agencyUserIds);
        return CollStreamUtil.toMap(list, AgencyUserVO::getId, dto -> dto);
    }

}
